<template>
  <div class="contioner">
    <!-- 头部搜索、添加 -->
    <div class="header">
      <el-card shadow="always" style="height: 90%" align="center">
        <span>姓名：</span>
        <el-input
          v-model="input1"
          placeholder="请输入姓名"
          style="width: 30%"
        ></el-input>
        <span>学号：</span>
        <el-input
          v-model="input2"
          placeholder="请输入学号"
          style="width: 30%"
        ></el-input>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="primary" @click="toAdd">添加</el-button>
        <el-button type="primary" @click="refresh">刷新</el-button>
      </el-card>
    </div>
    <!-- 中部表格展示 -->
    <div class="content">
      <el-table
        :data="pageTicket"
        style="width: 100%"
        height="100%"
        align="center"
      >
        <el-table-column
          prop="studentName"
          label="姓名"
          align="center"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="studentId"
          label="学号"
          align="center"
          width="160"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="phoneNumber"
          label="手机号"
          width="210"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="email"
          label="邮箱"
          width="210"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="accountStatus"
          label="账号状态"
          width="160"
        ></el-table-column>
        <el-table-column label="操作" width="170" align="center">
          <template slot-scope="scope">
            <el-button @click="toUpdate(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button @click="toDelete(scope.row.id)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部分页 -->
    <div class="footer">
      <el-pagination
        :current-page="params.page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[6, 12, 18, 24]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 弹出编辑框 -->
    <div class="overlay" v-if="isShow"></div>
    <div class="studentEdit" v-if="isShow">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="form.studentName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" id="passwordInput" show-password></el-input>
        </el-form-item>
        <el-form-item label="重复密码" prop="password1">
          <el-input v-model="form.password1" type="password" id="passwordInput1" show-password></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form.studentId"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="账号状态" prop="accountStatus">
          <el-select v-model="form.accountStatus">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="submit" @click="onSubmit('form')">修改</el-button>
          <el-button @click="cancel">取消</el-button>
          <el-button @click="togglePassword">显示密码</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 弹出添加表单 -->
    <div class="overlay1" v-if="isShow1"></div>
    <div class="studentAdd" v-if="isShow1">
      <el-form ref="form1" :model="form1" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="studentName">
          <el-input v-model="form1.studentName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form1.password" type="password" id="passwordInput" show-password></el-input>
        </el-form-item>
        <el-form-item label="重复密码" prop="password1">
          <el-input v-model="form1.password1" type="password" id="passwordInput1" show-password></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="form1.studentId"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form1.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form1.email"></el-input>
        </el-form-item>
        <el-form-item label="账号状态" prop="accountStatus">
          <el-select v-model="form1.accountStatus">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="submit" @click="onSubmit1('form1')">添加</el-button>
          <el-button @click="cancel1">取消</el-button>
          <el-button @click="togglePassword">显示密码</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import instance from "@/utils/request.js";
import { updateStudents } from "@/api/students";
import { addStudents } from "@/api/students";
export default {
  data() {
    //正则表达式
    var checkPhone = (rule, value, callback) => {
      const reg = /^1[0-9][0-9]\d{8}$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入正确的电话号码"));
        } else {
          callback();
        }
      }
    };
    var checkEmail = (rule, value, callback) => {
      const reg =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入正确的邮箱"));
        } else {
          callback();
        }
      }
    };
    var checkPassword = (rule, value, callback) => {
      const reg = /^[0-9a-zA-Z]*$/;
      if (!value) {
        return callback(new Error("password不能为空"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入正确的密码"));
        } else {
          callback();
        }
      }
    };
    var checkStudentId = (rule, value, callback) => {
      const reg = /^\d{11}$/;
      if (!value) {
        return callback(new Error("学号不能为空"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入正确的学号"));
        } else {
          callback();
        }
      }
    };
    var checkAccountStatus = (rule, value, callback) => {
      const reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("账号状态不能为空"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入正确的账号状态"));
        } else {
          callback();
        }
      }
    };
    var checkStudentName = (rule, value, callback) => {
      const reg = /^[\u4e00-\u9fa5]+$/;
      if (!value) {
        return callback(new Error("姓名不能为空"));
      } else {
        if (!reg.test(value)) {
          callback(new Error("请输入正确的姓名"));
        } else {
          callback();
        }
      }
    };
    return {
      input2: "",
      input1: "",
      pageTicket: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 6,
      },
      form: {
        studentName: "",
        studentId: "",
        phoneNumber: "",
        email: "",
        accountStatus: "",
        password: "",
        password1: "",
      },
      isShow: false,
      id: "",
      form1: {
        password: "",
        studentName: "",
        studentId: "",
        phoneNumber: "",
        email: "",
        accountStatus: "",
        password1: "",
      },
      isShow1: false,
      valid: "",
      rules: {
        password: [{ validator: checkPassword, trigger: "change" }],
        studentName: [{ validator: checkStudentName, trigger: "change" }],
        studentId: [{ validator: checkStudentId, trigger: "change" }],
        phoneNumber: [{ validator: checkPhone, trigger: "change" }],
        email: [{ validator: checkEmail, trigger: "change" }],
        accountStatus: [{ validator: checkAccountStatus, trigger: "change" }],
        password1: [{ validator: checkPassword, trigger: "change" }],
      },
    };
  },
  methods: {
    //搜索用户
    search() {
      //调用接口，将input1的值传递给后端，获取数据，赋值给pageTicket，total，
      instance
        .get("/api/ss?studentName=" + this.input1 + "&studentId=" + this.input2)
        .then((res) => {
          console.log(res);
          this.pageTicket = res.data;
          this.total = res.data.length;
        });
    },
    //搜索完后重置
    refresh() {
      this.getArticle();
      this.input1 = "";
      this.input2 = "";
    },
    //改变每页显示条数
    handleSizeChange(pageSize) {
      this.params.page = 1;
      this.params.pageSize = pageSize;
      this.getArticle();
    },
    //改变当前页码
    handleCurrentChange(page) {
      this.params.page = page;
      this.getArticle();
    },
    //将page、pageSize、查询条件对象传给后端
    getArticle() {
      // 分页对象属性和条件对象属性全部传给后端
      const temp = {
        ...this.params,
      };
      // 判断条件是否存在 存在 -- 传   不存在 -- 不传
      for (const key in temp) {
        if (!temp[key]) {
          delete temp[key];
        }
      }
      //调用接口，将page、pageSize传递给后端，获取数据，赋值给pageTicket，total，
      instance
        .get(
          "/api/pageQuery?page=" +
            this.params.page +
            "&pageSize=" +
            this.params.pageSize
        )
        .then((res) => {
          console.log(res);
          this.pageTicket = res.data.students;
          this.total = res.data.total;
        });
    },
    //删除
    toDelete(id) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          //调用接口，将id传递给后端，删除数据
          instance.delete("/api/deleteById?id=" + id).then((res) => {
            console.log(res);
            this.getArticle();
          });
          //提示删除成功
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑，弹出修改表单，将id号传递给后端,获取整行数据，赋值给form表单以供修改
    toUpdate(row) {
      this.isShow = true;
      this.id = row.id;
      instance.get("/api/students?id=" + row.id).then((res) => {
        console.log(res);
        this.form = res.data[0];
        // this.form.password1 = res.data[0].password;
        //小bug，修改密码时，如果密码不为空，从后段拿到密码赋值给重复密码框，则重复密码框不能进行修改，
        //需要先点击一下重复密码框，进行操作，此时并没有结果，然后再点击一下密码框，进行操作，重复密码框的值才能修改
      });
    },
    //先进行表单验证，通过后调用接口，将id号和修改后的数据传递给后端，修改数据
    onSubmit(form) {
      //判断两次密码是否一致
      if (this.form.password != this.form.password1) {
        this.$message({ type: "warning", message: "两次密码不一致！" });
        return false;
      }else{
      // valid在全部validator通过才会返回true，否则为false
      this.$refs[form].validate((valid) => {
        if (!valid) {
          this.$message({ type: "warning", message: "请修改正确的数据格式！" });
          return false;
        } else{ 
            console.log(this.form);
            updateStudents({
              id: this.id,
              studentName: this.form.studentName,
              studentId: this.form.studentId,
              phoneNumber: this.form.phoneNumber,
              email: this.form.email,
              accountStatus: this.form.accountStatus,
              password: this.form.password,
            }).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.isShow = false;
                this.getArticle();
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
              } else if (res.code == 414) {
                this.$message({
                  type: "error",
                  message: "修改失败! 学号重复,请重新输入",
                });
              } else if (res.code == 415) {
                this.$message({
                  type: "error",
                  message: "修改失败! 手机号重复,请重新输入",
                });
              } else if (res.code == 416) {
                this.$message({
                  type: "error",
                  message: "修改失败! 邮箱重复,请重新输入",
                });
              }
            });
          
        }
      });
  }},
    //取消修改
    cancel() {
      this.isShow = false;
      this.$message({
        type: "info",
        message: "取消修改",
      });
    },
    //添加，弹出到添加表单
    toAdd() {
      this.isShow1 = true;
    },
    //获取添加的数据，调用接口，将新的学号传递给后端，添加数据，重新获取数据
    onSubmit1(form1) {
      //验证密码输入的是否一致
      if (this.form1.password != this.form1.password1) {
        this.$message({ type: "warning", message: "两次密码不一致！" });
        return false;
      }else{
      this.$refs[form1].validate((valid) => {
        if (!valid) {
          console.log("error submit!!");
          this.$message({ type: "warning", message: "请修改正确的数据格式！" });
          return false;
        } else {
          if (form1.password != form1.password1) {
            this.$message({ type: "warning", message: "两次密码不一致！" });
            return false;
          } else {
            console.log(this.form1);
            addStudents({
              password: this.form1.password,
              studentName: this.form1.studentName,
              studentId: this.form1.studentId,
              phoneNumber: this.form1.phoneNumber,
              email: this.form1.email,
              accountStatus: this.form1.accountStatus,
            }).then((res) => {
              console.log(res);
              if (res.code == 200) {
                this.isShow1 = false;
                this.getArticle();
                this.$message({
                  type: "success",
                  message: "添加成功!",
                });
              } else if (res.code == 411) {
                this.$message({
                  type: "error",
                  message: "添加失败! 学号已存在,请重新输入",
                });
              } else if (res.code == 412) {
                this.$message({
                  type: "error",
                  message: "添加失败! 手机号已存在,请重新输入",
                });
              } else if (res.code == 413) {
                this.$message({
                  type: "error",
                  message: "添加失败! 邮箱已存在,请重新输入",
                });
              }
            });
          }
        }
      });
    }},
    //取消添加
    cancel1() {
      this.isShow1 = false;
      this.$message({
        type: "info",
        message: "取消添加",
      });
    },
    //显示密码,使用函数，或者直接添加属性show-password点击眼睛图标，密码显示为明文，再次点击，密码显示为密文
    togglePassword(){
      var abc = document.getElementById('passwordInput');
      var abc1 = document.getElementById('passwordInput1');
      if (abc.type === 'password') {
        abc.type = 'text';
      }else{
        abc.type = 'password';
      }
      if (abc1.type === 'password') {
        abc1.type = 'text';
      }else{
        abc1.type = 'password';
      }
    },
  },
  created() {
    this.getArticle();
  },
};
</script>
<style lang="less" scoped>
.contioner {
  width: 100%;
  height: 75vh;
  .header {
    width: 100%;
    height: 15%;
    span {
      font-weight: 600;
      font-size: 18px;
    }
    .el-card .el-input {
      margin-right: 15px;
    }
    .el-card {
      box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
    }
  }
  .content {
    width: 100%;
    height: 75%;
    //阴影效果去除，否则遮罩层会有一条白线，同时去除边框
    .el-table
      el-table--fit
      el-table--scrollable-x
      el-table--enable-row-hover
      el-table--enable-row-transition {
      z-index: 0;
    }
    .el-table--border::after,
    .el-table--group::after,
    .el-table::before {
      z-index: 0;
    }
  }
  .footer {
    width: 100%;
    height: 7%;
    margin-top: 10px;
    background-color: #fff;
    //阴影效果
    box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
    //圆滑边框
    border-radius: 4px;
    text-align: right;
  }
  /* 遮罩层样式 */
  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  /* 弹窗样式 */
  .studentEdit {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
  }
  /* 遮罩层样式 */
  .overlay1 {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  /* 弹窗样式 */
  .studentAdd {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
  }
}
</style>